﻿using System;

namespace Microsoft.Coding4Fun.TweetCraft
{
    internal static class ObjectExtensions
    {
        public static void Dispose(this object instance)
        {
            var disposableInstance = instance as IDisposable;
            if (disposableInstance != null)
                disposableInstance.Dispose();
        }

        public static void SubscribeError(this object instance, IErrorHandler errorHandler)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (errorHandler == null)
                throw new ArgumentNullException("errorHandler");

            var errorReporter = instance as IReportsError;
            if (errorReporter != null)
                errorReporter.Error += errorHandler.OnError;
        }

        public static void UnsubscribeError(this object instance, IErrorHandler errorHandler)
        {
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (errorHandler == null)
                throw new ArgumentNullException("errorHandler");

            var errorReporter = instance as IReportsError;
            if (errorReporter != null)
                errorReporter.Error -= errorHandler.OnError;
        }
    }
}
